<template>
    <view class="page">
        <!-- 页面头部 -->
        <view class="page-header">
            <view class="header-content">
                <view class="back-btn" @tap="back">
                    <tui-icon name="arrowleft" color="#fff" :size="20"></tui-icon>
                </view>
                <view class="header-title-section">
                    <text class="header-title">{{ pageTitle }}</text>
                    <text class="header-subtitle">{{ type === 1 ? '找到让你心动的人' : type === 2 ? '收藏的优质用户' : '最近访问的用户' }}</text>
                </view>
                <view class="header-right">
                </view>
            </view>
        </view>

        <!-- 搜索区域 -->
        <view class="search-section">
            <view class="search-container">
                <view class="search-input-wrapper">
                    <tui-icon name="search" :size="32" unit="rpx" color="#999" class="search-icon"></tui-icon>
                    <input 
                        class="search-input" 
                        placeholder="搜索姓名或手机号" 
                        placeholder-class="search-placeholder"
                        v-model="inputVal" 
                        @input="handleSearchInput"
                        @confirm="handleSearch"
                        :focus="searchFocus"
                    />
                    <tui-icon 
                        v-if="inputVal" 
                        name="close" 
                        :size="28" 
                        unit="rpx" 
                        color="#999" 
                        class="clear-icon"
                        @tap="clearInput"
                    ></tui-icon>
                </view>
                <view class="search-btn" @tap="handleSearch">
                    <text class="search-btn-text">搜索</text>
                </view>
            </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
            <tui-loading :size="40" unit="rpx" color="#FF6B35"></tui-loading>
            <text class="loading-text">加载中...</text>
        </view>

        <!-- 内容区域 -->
        <scroll-view 
            v-else
            class="content-scroll" 
            scroll-y 
            @scrolltolower="loadMore" 
            :refresher-enabled="true" 
            :refresher-triggered="refreshing" 
            @refresherrefresh="onRefresh"
        >
            <!-- 有数据时显示列表 -->
            <template v-if="visitorList.length > 0">
                <!-- 搜索结果 -->
                <view v-if="inputShowed" class="search-results">
                    <view class="result-header">
                        <text class="result-count">找到 {{searchResult.length}} 个结果</text>
                    </view>
                    <view class="user-list">
                        <view 
                            class="user-item" 
                            v-for="(item, index) in searchResult" 
                            :key="index" 
                            @tap="viewProfile(item)"
                        >
                            <view class="user-avatar-wrapper">
                                <image 
                                    :src="getUserAvatar(item)" 
                                    class="user-avatar"
                                    mode="aspectFill"
                                    @error="handleImageError"
                                    @load="handleImageLoad"
                                ></image>
                                <view v-if="item.isOnline" class="online-indicator"></view>
                            </view>
                            <view class="user-info">
                                <view class="user-name-wrapper">
                                    <text class="user-name">{{item.name || '未设置'}}</text>
                                    <view v-if="item.vip" class="vip-badge">VIP</view>
                                </view>
                                <view class="user-details">
                                    <text class="user-career" v-if="item.career">{{item.career}}</text>
                                    <text class="user-degree" v-if="item.degree">{{item.degree}}</text>
                                </view>
                                <view class="user-stats">
                                    <text class="stat-item">评分: {{item.rate || 0}}分</text>
                                    <text class="stat-item">浏览: {{item.pv || 0}}</text>
                                </view>
                                <view class="user-tags" v-if="getUserTags(item).length">
                                    <text class="tag" v-for="tag in getUserTags(item)" :key="tag">{{tag}}</text>
                                </view>
                            </view>
                            <view class="user-actions">
                                <view class="action-btn hi-btn" @tap.stop="sendHi(item)">
                                    <text class="btn-text">Hi</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 普通列表 -->
                <view v-else class="user-list">
                    <view 
                        class="user-item" 
                        v-for="(visitor, index) in visitorList" 
                        :key="index" 
                        @tap="viewProfile(visitor)"
                    >
                        <view class="user-avatar-wrapper">
                            <image 
                                :src="getUserAvatar(visitor)" 
                                class="user-avatar"
                                mode="aspectFill"
                                @error="handleImageError"
                                @load="handleImageLoad"
                            ></image>
                            <view v-if="visitor.isOnline" class="online-indicator"></view>
                        </view>
                        <view class="user-info">
                            <view class="user-name-wrapper">
                                <text class="user-name">{{ visitor.name || '未设置' }}</text>
                                <view v-if="visitor.vip" class="vip-badge">VIP</view>
                            </view>
                            <view class="user-details">
                                <text class="user-career" v-if="visitor.career">{{ visitor.career }}</text>
                                <text class="user-degree" v-if="visitor.degree">{{ visitor.degree }}</text>
                            </view>
                            <view class="user-stats">
                                <text class="stat-item">评分: {{visitor.rate || 0}}分</text>
                                <text class="stat-item">浏览: {{visitor.pv || 0}}</text>
                            </view>
                            <view class="user-tags" v-if="getUserTags(visitor).length">
                                <text class="tag" v-for="tag in getUserTags(visitor)" :key="tag">{{tag}}</text>
                            </view>
                        </view>
                        <view class="user-actions">
                            <view class="action-btn hi-btn" @tap.stop="sendHi(visitor)">
                                <text class="btn-text">Hi</text>
                            </view>
                        </view>
                    </view>
                </view>
            </template>

            <!-- 无数据时显示空状态 -->
            <view v-else class="empty-container">
                <image :src="getEmptyImage()" class="empty-image" mode="aspectFit"></image>
                <text class="empty-title">{{ type === 1 ? '暂无点赞记录' : type === 2 ? '暂无收藏记录' : '暂无来访记录' }}</text>
                <text class="empty-desc">{{ type === 1 ? '当你点赞其他用户时，会显示在这里' : type === 2 ? '当你收藏其他用户时，会显示在这里' : '当有人查看你的资料时，会显示在这里' }}</text>
                <view class="empty-action" @tap="goToDiscover">
                    <text class="action-text">去发现</text>
                </view>
            </view>

            <!-- 加载更多 -->
            <view v-if="loading" class="loading-more">
                <text class="loading-text">加载中...</text>
            </view>
        </scroll-view>
    </view>
</template>

<script>
	import empty from "./../components/empty.vue"
    import cfg from '@/common/config.js'
    
	export default {
		components: {
			empty
		},
		data() {
			return {
                visitorList: [],
                loading: false,
                refreshing: false,
                pageNo: 1,
                pageSize: 20,
                hasMore: true,
                total: 0,
                type: 1, // 1=点赞, 2=收藏
                pageTitle: '最近来访',
                // 搜索相关
                inputShowed: false,
                inputVal: '',
                searchResult: [],
                searchFocus: false,
                searchTimer: null,
                winHeight: 0
            }
        },
        onLoad(options) {
            // 获取传入的参数
            if (options.type) {
                this.type = parseInt(options.type)
            }
            if (options.title) {
                this.pageTitle = decodeURIComponent(options.title)
            }
            this.initPage()
            this.loadVisitors()
        },
        onUnload() {
            // 清理定时器
            if (this.searchTimer) {
                clearTimeout(this.searchTimer)
            }
        },
        onShow() {
            // 页面显示时刷新数据
            this.refreshData()
        },
        methods: {
            // 初始化页面
            initPage() {
                const that = this
                uni.getSystemInfo({
                    success: function (res) {
                        let winHeight = res.windowHeight
                        // 减去头部和搜索区域的高度
                        let contentHeight = winHeight - uni.upx2px(200)
                        that.winHeight = contentHeight
                    }
                })
            },

            // 返回上一页
            back() {
                uni.navigateBack()
            },

            // 加载来访者列表
            loadVisitors() {
                if (this.loading || !this.hasMore) return
                
                this.loading = true
                // 根据type参数调用不同的API
                if (this.type === 1 || this.type === 2) {
                    // 点赞或收藏列表
                    this.$api.getDatingRelativeList({
                        pageNo: this.pageNo,
                        pageSize: this.pageSize,
                        type: this.type
                    }).then(res => {
                        if (res.code === 0) {
                            const newList = res.data.list || []
                            if (this.pageNo === 1) {
                                this.visitorList = newList
                            } else {
                                this.visitorList = this.visitorList.concat(newList)
                            }
                            this.total = res.data.total || 0
                            this.hasMore = this.visitorList.length < this.total
                            
                            // 处理用户数据
                            newList.forEach(item => {
                                item.isOnline = Math.random() > 0.5
                                item.lastVisitTime = new Date().toISOString() // 模拟访问时间
                            })
                        } else {
                            uni.showToast({
                                title: res.msg || '加载失败',
                                icon: 'none'
                            })
                        }
                    }).catch(err => {
                        console.error('加载列表失败:', err)
                        uni.showToast({
                            title: '网络错误',
                            icon: 'none'
                        })
                    }).finally(() => {
                        this.loading = false
                        this.refreshing = false
                    })
                } else {
                    // 原来的最近来访逻辑
                    this.$api.getDatingMemberPage({
                        pageNo: this.pageNo,
                        pageSize: this.pageSize,
                        queryType: 'recent',
                        orderBy: 'pv',
                        orderDirection: 'desc'
                    }).then(res => {
                        if (res.code === 0) {
                            const newList = res.data.list || []
                            if (this.pageNo === 1) {
                                this.visitorList = newList
                            } else {
                                this.visitorList = this.visitorList.concat(newList)
                            }
                            this.total = res.data.total || 0
                            this.hasMore = this.visitorList.length < this.total
                            
                            // 处理用户数据
                            newList.forEach(item => {
                                item.isOnline = Math.random() > 0.5
                                item.lastVisitTime = new Date().toISOString() // 模拟访问时间
                            })
                        } else {
                            uni.showToast({
                                title: res.msg || '加载失败',
                                icon: 'none'
                            })
                        }
                    }).catch(err => {
                        console.error('加载来访者列表失败:', err)
                        uni.showToast({
                            title: '网络错误',
                            icon: 'none'
                        })
                    }).finally(() => {
                        this.loading = false
                        this.refreshing = false
                    })
                }
            },

            // 加载更多
            loadMore() {
                if (this.hasMore && !this.loading) {
                    this.pageNo++
                    this.loadVisitors()
                }
            },

            // 下拉刷新
            onRefresh() {
                this.refreshing = true
                this.pageNo = 1
                this.hasMore = true
                this.loadVisitors()
            },

            // 刷新数据
            refreshData() {
                this.pageNo = 1
                this.hasMore = true
                this.loadVisitors()
            },

            // 查看用户资料
            viewProfile(visitor) {
                this.f.nav(`/subPackage1/marriageDetail/marriageDetail?id=${visitor.userId}`)
            },

            // 发送Hi
            sendHi(visitor) {
                this.f.nav(`/subPackage1/chat/chat?userId=${visitor.userId}&name=${visitor.name}`)
            },



            // 搜索输入处理（防抖）
            handleSearchInput(e) {
                this.inputVal = e.detail.value
                
                // 清除之前的定时器
                if (this.searchTimer) {
                    clearTimeout(this.searchTimer)
                }
                
                // 设置防抖
                this.searchTimer = setTimeout(() => {
                    this.performSearch()
                }, 300)
            },

            // 执行搜索
            performSearch() {
                if (!this.inputVal.trim()) {
                    this.inputShowed = false
                    this.searchResult = []
                    return
                }
                
                const keyword = this.inputVal.trim().toUpperCase()
                const result = []
                
                this.visitorList.forEach(user => {
                    const searchKeyword = (user.name || '').toUpperCase() + (user.mobile || '')
                    if (searchKeyword.includes(keyword)) {
                        result.push(user)
                    }
                })
                
                this.inputShowed = true
                this.searchResult = result
            },

            // 搜索按钮点击
            handleSearch() {
                this.performSearch()
            },

            // 清空搜索
            clearInput() {
                this.inputVal = ''
                this.inputShowed = false
                this.searchResult = []
                this.searchFocus = false
            },

            // 去发现页面
            goToDiscover() {
                uni.switchTab({
                    url: '/pages/index/index'
                })
            },

            // 获取用户标签
            getUserTags(user) {
                const tags = []
                
                // 根据出生日期计算年龄
                if (user.birth) {
                    const birthDate = new Date(user.birth)
                    const now = new Date()
                    const age = now.getFullYear() - birthDate.getFullYear()
                    if (age > 0 && age < 100) {
                        tags.push(`${age}岁`)
                    }
                }
                
                // 职业
                if (user.career) {
                    tags.push(user.career)
                }
                
                // 学历
                if (user.degree) {
                    tags.push(user.degree)
                }
                
                // 性别
                if (user.sex) {
                    tags.push(user.sex === 1 ? '男' : '女')
                }
                
                return tags.slice(0, 3) // 最多显示3个标签
            },

            // 获取空状态图片
            getEmptyImage() {
                if (this.type === 1) {
                    return '/static/images/empty-heart.png'
                } else if (this.type === 2) {
                    return '/static/images/empty-star.png'
                } else {
                    return '/static/images/empty-visitor.png'
                }
            },

            // 图片加载成功
            handleImageLoad(e) {
                // 图片加载成功
            },

            // 图片加载失败
            handleImageError(e) {
                // 图片加载失败，可以在这里设置默认头像
            },

            // 获取用户头像
            getUserAvatar(user) {
                // 处理头像URL，参考heartbeat页面的逻辑
                let avatarUrl = '/static/img/tabs/my.png'
                
                if (user.cover && typeof user.cover === 'string') {
                    try {
                        // 先去掉首尾的方括号，然后解析JSON
                        let coverStr = user.cover.trim()
                        
                        // 如果首尾是方括号，去掉它们
                        if (coverStr.startsWith('[') && coverStr.endsWith(']')) {
                            coverStr = coverStr.slice(1, -1)
                        }
                        
                        // 现在解析JSON数组
                        const coverArray = JSON.parse('[' + coverStr + ']')
                        
                        // 检查是否为数组且有数据
                        if (Array.isArray(coverArray) && coverArray.length > 0) {
                            avatarUrl = coverArray[0]
                        }
                    } catch (e) {
                        // 如果JSON解析失败，尝试直接提取URL
                        const urlMatch = user.cover.match(/https?:\/\/[^\]]+/)
                        if (urlMatch) {
                            avatarUrl = urlMatch[0]
                        }
                    }
                } else if (user.cover && Array.isArray(user.cover) && user.cover.length > 0) {
                    avatarUrl = user.cover[0]
                }
                
                return avatarUrl
            },

            // 格式化年龄
            formatAge(birthDate) {
                if (!birthDate) return ''
                const birth = new Date(birthDate)
                const today = new Date()
                let age = today.getFullYear() - birth.getFullYear()
                const monthDiff = today.getMonth() - birth.getMonth()
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
                    age--
                }
                return age
            },

            // 格式化访问时间
            formatVisitTime(timeStr) {
                if (!timeStr) return '刚刚'
                const time = new Date(timeStr)
                const now = new Date()
                const diff = now - time
                const minutes = Math.floor(diff / 60000)
                const hours = Math.floor(diff / 3600000)
                const days = Math.floor(diff / 86400000)
                
                if (minutes < 1) return '刚刚'
                if (minutes < 60) return `${minutes}分钟前`
                if (hours < 24) return `${hours}小时前`
                if (days < 7) return `${days}天前`
                return time.toLocaleDateString()
            }
		}
	}
</script>

<style lang="scss" scoped>
    page {
        height: 100%;
        background: #f8f9fa;
    }

    .page {
        height: 100%;
        display: flex;
        flex-direction: column;
        background: #f8f9fa;
    }

    /* 页面头部 */
    .page-header {
        background: linear-gradient(135deg, #a55fee, #c77dff);
        padding: 40rpx 30rpx 30rpx;
        color: white;
    }

    .header-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .back-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
    }

    .header-title-section {
        flex: 1;
        margin: 0 20rpx;
    }

    .header-title {
        font-size: 36rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
        display: block;
    }

    .header-subtitle {
        font-size: 26rpx;
        opacity: 0.9;
        display: block;
    }

    .header-right {
        width: 60rpx;
        display: flex;
        justify-content: flex-end;
    }


    /* 搜索区域 */
    .search-section {
        background: white;
        padding: 20rpx 30rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .search-container {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }

    .search-input-wrapper {
        flex: 1;
        position: relative;
        background: #f5f5f5;
        border-radius: 25rpx;
        padding: 0 20rpx;
        height: 70rpx;
        display: flex;
        align-items: center;
    }

    .search-icon {
        margin-right: 15rpx;
    }

    .search-input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
        color: #333;
        background: transparent;
        border: none;
        outline: none;
    }

    .search-placeholder {
        color: #999;
        font-size: 28rpx;
    }

    .clear-icon {
        margin-left: 15rpx;
        padding: 10rpx;
    }

    .search-btn {
        background: #a55fee;
        border-radius: 25rpx;
        padding: 0 30rpx;
        height: 70rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 120rpx;
    }

    .search-btn-text {
        color: white;
        font-size: 28rpx;
        font-weight: 500;
    }

    /* 加载状态 */
    .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 100rpx 0;
    }

    .loading-text {
        margin-top: 20rpx;
        font-size: 28rpx;
        color: #666;
    }

    /* 内容滚动区域 */
    .content-scroll {
        flex: 1;
        background: #f8f9fa;
    }

    /* 搜索结果 */
    .search-results {
        background: white;
        margin: 20rpx;
        border-radius: 16rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .result-header {
        padding: 20rpx 30rpx;
        background: #f8f9fa;
        border-bottom: 1rpx solid #eee;
    }

    .result-count {
        font-size: 26rpx;
        color: #666;
    }

    /* 空状态 */
    .empty-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 120rpx 60rpx;
        text-align: center;
    }

    .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
    }

    .empty-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 16rpx;
    }

    .empty-desc {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 40rpx;
        line-height: 1.5;
    }

    .empty-action {
        background: #a55fee;
        color: white;
        padding: 20rpx 40rpx;
        border-radius: 25rpx;
        font-size: 28rpx;
        font-weight: 500;
    }

    .action-text {
        color: white;
    }

    /* 用户列表 */
    .user-list {
        background: white;
        border-radius: 16rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        margin: 20rpx;
    }

    .user-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #f0f0f0;
        transition: background-color 0.2s;
    }

    .user-item:last-child {
        border-bottom: none;
    }

    .user-item:active {
        background-color: #f8f9fa;
    }

    .user-avatar-wrapper {
        position: relative;
        margin-right: 24rpx;
    }

    .user-avatar {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        border: 3rpx solid #f0f0f0;
    }

    .online-indicator {
        position: absolute;
        bottom: 5rpx;
        right: 5rpx;
        width: 20rpx;
        height: 20rpx;
        background: #4CAF50;
        border-radius: 50%;
        border: 3rpx solid white;
    }

    .user-info {
        flex: 1;
        min-width: 0;
    }

    .user-name-wrapper {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
    }

    .user-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 12rpx;
    }

    .vip-badge {
        background: linear-gradient(135deg, #ffd700, #ffed4e);
        color: #8b4513;
        font-size: 18rpx;
        font-weight: 600;
        padding: 2rpx 8rpx;
        border-radius: 8rpx;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
    }

    .user-details {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
        gap: 16rpx;
    }

    .user-career {
        font-size: 24rpx;
        color: #666;
        background: #f0f0f0;
        padding: 2rpx 8rpx;
        border-radius: 6rpx;
    }

    .user-degree {
        font-size: 24rpx;
        color: #666;
        background: #e8f4fd;
        padding: 2rpx 8rpx;
        border-radius: 6rpx;
    }

    .user-stats {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
        gap: 20rpx;
    }

    .stat-item {
        font-size: 22rpx;
        color: #999;
    }

    .user-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8rpx;
    }

    .tag {
        background: #a55fee;
        color: white;
        font-size: 20rpx;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
    }

    .user-actions {
        display: flex;
        flex-direction: column;
        gap: 12rpx;
        margin-left: 20rpx;
    }

    .action-btn {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
    }

    .hi-btn {
        background: #a55fee;
    }

    .hi-btn:active {
        background: #8e4bc7;
        transform: scale(0.95);
    }


    .btn-text {
        color: white;
        font-size: 24rpx;
        font-weight: 600;
    }

    /* 加载更多 */
    .loading-more {
        display: flex;
        justify-content: center;
        padding: 40rpx;
    }

    .loading-text {
        font-size: 26rpx;
        color: #999;
	}
</style>
